<?php

namespace App\Models;

use App\Jobs\SendChangeOrderMessage;
use App\Services\AlipayMessageService;
use App\Services\AlipayMiniOrderService;
use App\Services\CommonService;
use App\Services\EducationService;
use App\Services\OrderService;
use App\Services\RedisLock;
use App\Services\RedisService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Testing\Fluent\Concerns\Has;

class OrderDlzwRisk extends Model
{
    use HasFactory;
    protected $table = 'sp_order_dlzw_risk';
    protected $primaryKey = 'id';
    public $timestamps = false;
    //查询地区信息


    public static function getUserDLzwRisk($order_id)
    {
        $one= self::where('order_id',$order_id)->orderBy('id','desc')->select('create_time','risk_level','result')->first();
        if(empty($one['risk_level'])){
            return '';
        }
        $one['create_time']=date('Y-m-d H:i:s',$one['create_time']);
        $result=json_decode($one['result'],true);
        $data=$result['data'];
        $pass=$data['result']=='1'?'通过':'不通过';
        $message='';
        if($data['level']){
            $message.='风险等级为'.$data['level'].'，';
        }
        if($data['ruleset_score']){
            $message.='权重分数为'.$data['ruleset_score'].'，';
        }
        if($data['quota_ratio']){
            $message.='额度评分'.$data['quota_ratio'].'，';
        }
        if($data['quota_val']){
            $message.='授信额度'.$data['quota_val'].'，';
        }
        if($data['risk_fail_code']){
            $message.='命中规则编号'.$data['risk_fail_code'];
        }

        $one['message']=$message;

        unset($one['result']);
        return $one;
    }

    public  function insertFlowMember($cert_no,$cert_name,$uid,$order_id,$data)
    {
        $data=[
            'cert_no'=>$cert_no,
            'cert_name'=>$cert_name,
            'order_id'=>$order_id,
            'uid'=>$uid,
            'flowNo'=>$data['meta']['sn']??'','create_time'=>time(),
            'risk_level'=>$data['data']['level']??'',
            'result'=>json_encode($data, JSON_UNESCAPED_UNICODE),
        ];
        $res=self::insert($data);

        return true;
    }

    public function orderClose($orderId){
        // dd($orderId);
        $redis = new RedisService();
        $lock = RedisLock::lock($redis, 'orderIdRefund'.$orderId);
        if(!$lock){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '系统繁忙，请稍后再试');
        }
        if(!empty($orderId)){
            $order_res = Order::noPayOrderCancel($orderId,false,false);
            if($order_res['status'] == CommonService::HTTP_CODE_SUCCESS){
                $add = [
                    'uid'=>23,
                    'username'=>'风控拒绝',
                    'create_time'=>time(),
                    'remark'=>'风控拒绝，关闭订单',
                    'order_id'=>$orderId
                ];
                OrderRemark::insert($add);
                Order::where('id',$orderId)->update(['order_fixed'=>1]);

                SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::CONSUMER);
                SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::KX_SHOPPING);

                RedisLock::unlock($redis, 'orderIdRefund'.$orderId);

                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'取消成功');
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $order_res['msg']);
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     * qn风控查询列表
     */
    public static function getRiskQnList($page,$pageSize, $input){

        if (!empty($input['cert_name'])) {
            $where[] = ['m.cert_name', $input['cert_name']];
        }
        if (!empty($input['mobile'])) {
            $where[] = ['m.mobile', 'like', '%' . trim($input['mobile']) . '%'];
        }
        if (!empty($input['cert_no'])) {
            $where[] = ['m.cert_no', 'like', '%' . trim($input['cert_no']) . '%'];
        }



        if (!empty($input['create_time'])) {
            $time = searchTime($input['create_time']);
            $where[] = ['mqr.create_time', '>=', strtotime($time['begin_time'])];
            $where[] = ['mqr.create_time', '<', strtotime($time['end_time'])];
        }

        if (!empty($input['shopname'])) {
            $member_id=ShopUser::where('shopname',$input['shopname'])->value('member_id');
            if($member_id){
                $where[] = ['o.seller_id', $member_id];
            }
        }

        if (!empty($input['is_fore'])&&$input['is_fore']==1) {
            $where[] = ['o.foregift_deduct', '>','0'];
        }
        if (!empty($input['is_fore'])&&$input['is_fore']==2) {
            $where[] = ['o.foregift_pay', '>','0'];
        }


        if (!empty($input['result'])) {
            $where[] = ['mqr.risk_result', $input['result']];
        }

        $RiskCredit=MemberDlzwRisk::from('sp_member_qnyp_risk as mqr')
            ->leftJoin('sp_member_2 as m','mqr.uid','m.id')
            ->leftJoin('sp_order_2 as o','o.uid','mqr.uid')
            ->groupBy('o.uid')
            ->orderBy('mqr.id','desc')
//            ->whereColumn('o.create_time', '<', 'mqr.create_time')
//            ->whereRaw('o.create_time > mqr.create_time - 100')
            ->where($where)
            ->select('m.sale_user_id','m.mobile','o.foregift_deduct','m.openId','m.contract_no','o.order_from','o.foregift','o.foregift_pay','o.seller_id','mqr.*')
            ->where($where);

        if($input['sale_user_id']&&is_array($input['sale_user_id'])){
            $RiskCredit->whereIn('m.sale_user_id',$input['sale_user_id']);
        }

        $RiskCredit = $RiskCredit->paginate($pageSize);

        foreach ($RiskCredit as $key=>$item) {
//            $item=Order::from('sp_order_2 as o')->where('o.id',$item['cert_no'])->orderBy('o.id','asc')
//                ->select('m.cert_no','o.order_from','m.openId','m.contract_no','o.sale_user_id','m.mobile','o.seller_id','o.seller_id',
//                    'o.foregift_deduct','o.foregift','o.foregift_pay')->first();
            $source = Source::where(['source_code' => $item['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
            if($item['order_from']=='saleOnline'&&$item['openId']){
                $source=$source.'-微信';
            }
            if($item['order_from']=='saleOnline'&&empty($item['openId'])){
                $source=$source.'-支付宝';
            }
            if($item['contract_no']){
                $source=$source.'-W';
            }
            $channel_name=SaleUser::where('sale_user_id',$item['sale_user_id'])->value('channel_name');
            if($channel_name){
                $source=$source.'-'.$channel_name;
            }
            if($item['sale_user_id']){
                $source=$source.'-'.$item['sale_user_id'];
            }
            $item['mobile']=$item['mobile'];
            $item['source']=$source;
            $item['status']=$item['risk_result']?'成功':'失败';
            $item['name']=ShopUser::where('member_id',$item['seller_id'])->value('shopname');
            $item['result2']=$item['risk_result']&&$item['risk_result']==10?'通过':'拒绝';
//            if($item['risk_level']){
//                $item['result2']=$item['result2'].'；风险等级'.$item['risk_level'];
//            }
            $item['create_time']=date('Y-m-d H:i:s',$item['create_time']);
            $item['req_id']=$item['flowNo'];

            $item['foregift_deduct']=$item['foregift_deduct'];
            $item['foregift']=$item['foregift'];
            $item['foregift_pay']=$item['foregift_pay'];
        }
        return $RiskCredit;
    }

    /**
     * qn风控查询列表
     */
    public static function getRiskQnListAll($page,$pageSize, $input){

        if (!empty($input['cert_name'])) {
            $where[] = ['m.cert_name', $input['cert_name']];
        }
        if (!empty($input['mobile'])) {
            $where[] = ['m.mobile', 'like', '%' . trim($input['mobile']) . '%'];
        }
        if (!empty($input['cert_no'])) {
            $where[] = ['m.cert_no', 'like', '%' . trim($input['cert_no']) . '%'];
        }


        if (!empty($input['create_time'])) {
            $time = searchTime($input['create_time']);
            $where[] = ['mqr.create_time', '>=', strtotime($time['begin_time'])];
            $where[] = ['mqr.create_time', '<', strtotime($time['end_time'])];
        }

        if (!empty($input['shopname'])) {
            $member_id=ShopUser::where('shopname',$input['shopname'])->value('member_id');
            if($member_id){
                $where[] = ['o.seller_id', $member_id];
            }
        }

        if (!empty($input['is_fore'])&&$input['is_fore']==1) {
            $where[] = ['o.foregift_deduct', '>','0'];
        }
        if (!empty($input['is_fore'])&&$input['is_fore']==2) {
            $where[] = ['o.foregift_pay', '>','0'];
        }


        if (!empty($input['result'])) {
            $where[] = ['mqr.risk_result', $input['result']];
        }


        $RiskCredit=MemberDlzwRisk::from('sp_member_qnyp_risk as mqr')
            ->leftJoin('sp_member_2 as m','mqr.uid','m.id')
            ->leftJoin('sp_order_2 as o','o.uid','mqr.uid')
            ->groupBy('o.uid')
            ->orderBy('mqr.id','desc')
//            ->whereColumn('o.create_time', '<', 'mqr.create_time')
            ->whereRaw('o.create_time > mqr.create_time - 100')
            ->where($where)
            ->select('m.sale_user_id','m.mobile','o.foregift_deduct','m.openId','m.contract_no','o.order_from','o.foregift','o.foregift_pay','o.seller_id','mqr.*')
            ->where($where);


        if($input['sale_user_id']&&is_array($input['sale_user_id'])){
            $RiskCredit->whereIn('m.sale_user_id',$input['sale_user_id']);
        }

        $RiskCredit = $RiskCredit->get()->toArray();

        $data=[];
        foreach ($RiskCredit as $key=>&$item) {

            $where=[];
            if (!empty($input['is_fore'])&&$input['is_fore']==1) {
                $where[] = ['o.foregift_deduct', '>','0'];
            }

//            $item=Order::from('sp_order_2 as o')->leftJoin('sp_member_2 as m','o.uid','m.id')->where('m.cert_no',$item['cert_no'])->orderBy('o.id','asc')
//                ->where($where)
//                ->select('m.cert_no','o.order_from','m.openId','m.contract_no','o.sale_user_id','m.mobile','o.seller_id','o.seller_id',
//                    'o.foregift_deduct','o.foregift','o.foregift_pay')->first();
            $source = Source::where(['source_code' => $item['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
            if($item['order_from']=='saleOnline'&&$item['openId']){
                $source=$source.'-微信';
            }
            if($item['order_from']=='saleOnline'&&empty($item['openId'])){
                $source=$source.'-支付宝';
            }
            if($item['contract_no']){
                $source=$source.'-W';
            }
            $channel_name=SaleUser::where('sale_user_id',$item['sale_user_id'])->value('channel_name');
            if($channel_name){
                $source=$source.'-'.$channel_name;
            }
            if($item['sale_user_id']){
                $source=$source.'-'.$item['sale_user_id'];
            }
            $data[$key]['req_id']="\t".$item['flowNo'];
            $data[$key]['cert_name']=$item['cert_name'];
            $data[$key]['cert_no']="\t".$item['cert_no'];
            $data[$key]['mobile']="\t".$item['mobile'];
            $data[$key]['name']=ShopUser::where('member_id',$item['seller_id'])->value('shopname');
            $data[$key]['status']=$item['risk_result']?'成功':'失败';
            $data[$key]['result2']=$item['risk_result']&&$item['risk_result']==10?'通过':'拒绝';
            $data[$key]['result3']=$item['risk_level'];
            $data[$key]['source']=$source;
            $data[$key]['foregift_deduct']=$item['foregift_deduct']>0?"完全免押":($item['foregift_pay']>0?"实付免押":'未免押');
            $data[$key]['create_time']=date('Y-m-d H:i:s',$item['create_time']);
        }
        return $data;
    }


}
